<?php

namespace App\Http\Controllers\Api;

use App\Models\Reservation;
use App\Models\ReservationComment;
use App\Models\ReservationOperateLogs;
use App\Models\ReservationServiceCategory;
use App\Models\SystemRegion;
use App\Models\User;
use App\Services\SensitiveWords;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ReservationController extends Controller
{

    /*
     * 预约服务的列表
     * @param Request $request
     * @return bool
     */
    public function index(Request $request)
    {
        $pagesize  = $request -> input('pagesize') ?? 5;
        //$region_id = $request -> input('region_id');
        $types     = $request -> input('types');
        $user_id   = $request -> input('user_id');

        // 获取农业服务分类表
        $reservationServiceCategory = ReservationServiceCategory::pluck('name','id') -> all();

        $reservation = Reservation::with(['reserver:id,user_name,real_name,head_portrait']) -> where('is_show','1') -> where(function($query)use($types){
            $types && $query -> where('types',$types);
        }) ->where(function ($query) use($user_id){

            if($user_id){
                $query -> where('user_id',$user_id);
            }/*else{
                if($region_id){
                    $query -> where('region_id',$region_id);
                }else{
                    $query -> where('region_id',0);
                    $query -> orWhere('region_id',null);
                }
            }*/
        })  -> paginate($pagesize);

        // 提取评论列表
        if($reservation){
            foreach($reservation as $k => $v){
                $v -> service_category_name = $reservationServiceCategory[$v -> service_category_id];
                if($v -> reserver){
                    if($v -> reserver -> real_name){
                        $v -> reserver -> user_name = $v -> reserver -> real_name;
                    }  unset($v -> reserver -> real_name);
                }
                $v -> reserver -> head_portrait_url = config('app.img_url').$v -> reserver -> head_portrait;
                if($v -> expert_user_id){

                    $v -> experter = User::select(['id','user_name','real_name','head_portrait']) -> find($v -> expert_user_id);
                    $v -> experter -> real_name && $v -> experter -> user_name = $v -> experter -> real_name;  unset($v -> experter -> real_name);
                    $v -> experter -> head_portrait_url = $v -> experter -> head_portrait;

                }else{
                    $v -> experter = null;
                }


                $v -> comments = ReservationComment::with(['commenter:id,user_name,real_name,head_portrait'])
                    -> where('is_expert',1) -> where('is_show',1)
                    -> where('reservation_id',$v -> id) -> orderBy('id','desc') -> first();

                if($v -> comments){
                    if($v -> comments -> commenter -> real_name){
                        $v -> comments -> commenter -> user_name = $v -> comments -> commenter -> real_name;
                    } unset($v -> comments -> commenter -> real_name);
                    $v -> comments -> commenter -> head_portrait_url = config('app.img_url').$v -> comments -> commenter -> head_portrait;

                }
            }
            return jsonSuccess($reservation);
        }else{
            return jsonSuccess();
        }
    }

    /*
     * 预约文章详情页
     * @return array
     */
    public function details(Request $request)
    {
        if($reservation_id = $request -> input('reservation_id')){


            $reservation = Reservation::with(['reserver:id,user_name,real_name,head_portrait']) -> where('id',$reservation_id) -> first();
            if($reservation){
                // 获取农业服务分类表
                $reservationServiceCategory = ReservationServiceCategory::pluck('name','id') -> all();


                $reservation -> service_category_id && $reservation -> service_category_name = $reservationServiceCategory[ $reservation -> service_category_id ];

                if($reservation -> reserver){
                    $reservation -> reserver -> real_name && $reservation -> reserver -> user_name = $reservation -> reserver -> real_name;   unset($reservation -> reserver -> real_name);
                    $reservation -> reserver -> head_portrait_url =  config('app.img_url').$reservation -> reserver -> head_portrait;
                }

                // 专家信息
                $reservation -> experter = User::where('id',$reservation -> expert_user_id) -> select(['id','user_name','real_name','head_portrait']) -> first();
                if($reservation -> experter -> real_name){
                    $reservation -> experter -> user_name = $reservation -> experter -> real_name;
                } unset($reservation -> experter -> real_name);
                $reservation -> experter -> head_portrait_url = config('app.img_url').$reservation -> experter -> head_portrait;



                // 评论列表，要求专家评论在前，普通用户在后
                $comment_list = ReservationComment::with(['commenter:id,user_name,real_name,head_portrait']) ->where('reservation_id',$reservation_id) ->where('is_show',1)
                       -> orderBy('is_expert','desc')
                       -> orderBy('zan_num','desc')
                       -> orderBy('created_at','desc') -> get();

                foreach($comment_list as $k => $v){
                    if($v -> commenter -> real_name){
                        $v -> commenter -> user_name = $v -> commenter -> real_name;
                    } unset($v -> commenter -> real_name);
                    $v -> commenter -> head_portrait_url = config('app.img_url').$v -> commenter -> head_portrait;
                    $comment_list[$k] = $v;
                }

                return jsonSuccess(['reservation' => $reservation,'comment_list' => $comment_list]);
            }else{
                return jsonSuccess();
            }
        }else{
            return jsonSuccess();
        }
    }


    /*
     * 预约服务的添加
     * @param Request $request
     * @return string
     */
    public function addReservation(Request $request)
    {

        $param  = $request -> all();

        $message = [
            'service_category_id.required' => '请选择农业服务分类',
            'expert_user_id.required' => '请选择专家',
            'content.required' => '请输入情况说明',
            'contact.required' => '请输入联系方式',
            'contact.regex' => '请输入正确的手机号',
        ];
        $validator = Validator::make($param,[
            'service_category_id' => 'required',
            'expert_user_id' => 'required',
            'content' => 'required',
            'contact' => ['required','regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
        ],$message);

        // 验证失败返回
        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }


        $bad_word = SensitiveWords::getBadWord($request -> input('content'));
        if (!empty($bad_word)) {
            return jsonError('请勿使用敏感词：'.current($bad_word));
        }

        if(!$param['imgs'] && !$param['video']){
            return jsonError('请添加图片、视频的一种');
        }


        $reservation = Reservation::store($param);

        if($reservation){
            return jsonSuccess(2007);
        }else{
            return jsonError();
        }
    }


    /*
     * 预约农业指导分类表
     * @return string
     */
    public function category()
    {

        $reservationCategory = ReservationServiceCategory::get();

        return jsonSuccess($reservationCategory);
    }


    /*
     * 农业专家列表
     * @param $request
     * @return string
    */
    public function expertList(Request $request)
    {

        $service_catid = $request -> input('service_catid');
        $region_id     = $request -> input('region_id');
        $role = '2'; // 角色：普通用户0, 乡村振兴员1，专家2

        if(!$request -> filled('service_catid')){
            return jsonSuccess();
        }


        $expertList = User::where('role',$role) -> where('service_catid',$service_catid)
           /* -> where(function ($query) use($region_id){
                if($region_id){
                    $region_code = SystemRegion::find($region_id) -> region_code;
                    $query -> where('region_code',$region_code);
                }
            })*/ -> get(['id','user_name','real_name','region_code','service_catid']);

            foreach($expertList as $v){
                if($v -> real_name){
                    $v -> user_name = $v -> real_name;
                }
                unset($v -> real_name);
            }


        return jsonSuccess($expertList);

    }


    /*
     * 预约评论
     * @return bool
     */
    public function comment(Request $request)
    {
        if(!$request -> filled('reservation_id') || !is_numeric($request -> input('reservation_id'))){
            return jsonError(4020);
        }

        if(!$request -> filled('content')){
            return jsonError(4036);
        }

        $bad_word = SensitiveWords::getBadWord($request -> input('content'));
        //dd('包含敏感词:' . current($bad_word),$bad_word);
        if (!empty($bad_word)) {
            return jsonError('请勿使用敏感词：'.current($bad_word));
        }

        $param = $request -> all();

        $res = ReservationComment::store($param);

        if($res){
            if($res['error']){ return jsonError($res['error']); }
            //操作记录
            ReservationOperateLogs::operateLog($param['reservation_id'],4,$res -> id);
            return jsonSuccess(2007);
        }else{
            return jsonError();
        }
    }


    /*
     * 预约操作表 operate_type: 点赞1 分享2
     * @return string
     */
    public function reservationOperateLogs(Request $request)
    {
        //验证
        if(!is_numeric($request -> input('operate_type')) || !$request -> input('operate_type')){
            return jsonError(4020);
        }

        // 预约文章id存在, 评论id不存在，对预约文章
        // 评论id存在，预约文章id存在，优先 对 评论 进行评论
        if($request -> input('reservation_id')){
            if(!is_numeric($request -> input('reservation_id'))){
                return jsonError(4020);
            }

            if(!Reservation::find($request -> input('reservation_id'))){
                return jsonError('',4000,404);
            }
        }
        $reservation_id = $request -> input('reservation_id');
        if($request -> input('comment_id')){
            if(!is_numeric($request -> input('comment_id'))){
                return jsonError(4020);
            }

            if(!ReservationComment::find($request -> input('comment_id'))){
                return jsonError('',4000,404);
            }

            if($reservation_id){
                $reservation_id = ReservationComment::where('id',$request -> input('comment_id')) ->value('reservation_id');
            }
        }

        $operate_type   = $request -> input('operate_type');

        // 对预约操纵
        $res = ReservationOperateLogs::operateLog($reservation_id,$operate_type,($request -> input('comment_id')?? 0));
        return jsonSuccess(2007);
    }

    /*
     * 查看更多评论
     * @return string
     */
    public function commentMore(Request $request)
    {
        $reservation_id = $request -> input('reservation_id');

        $commentMore = ReservationComment::with(['commenter:id,user_name,head_portrait']) ->where('reservation_id',$reservation_id) -> orderBy('id') -> get();

        foreach($commentMore as $k => $v){

            $v -> commenter -> head_portrait_url = config('app.img_url').$v -> commenter -> head_portrait;
            $commentMore[$k] = $v;
        }

        return jsonSuccess($commentMore);

    }

}
